var shareApi = 'https://api.w293.cn/'
var jyhsApi = 'https://api.jyhs.ls293.cn/'
var mealApi = 'https://api.meal.w293.cn/'

module.exports = {
   getJyhsApi: getJyhsApi,
   getShareApi: getShareApi,
   toast: toast,
   modal: modal,
   empty: empty,
   isArray: isArray,
   addValueForKey: addValueForKey,
   getIndexInList: getIndexInList,
   twoObjIsSame: twoObjIsSame,
   getLoc: getLoc,
   shareApi: shareApi,
   getNowFormatDate: getNowFormatDate,
   confirm: confirm,
   Toast: Toast,
   Modal: Modal,
   toastAllText: toastAllText,
   addMoneyRecord_User: addMoneyRecord_User,
   addMoneyRecord_Biz: addMoneyRecord_Biz,
   navigateBack: navigateBack,
   round: round,
   roundStr: roundStr,
   countSubString: countSubString,
   filterStr: filterStr,
   updateKeyForValue: updateKeyForValue,
   updateUserBalance: updateUserBalance,
   navigateBackWithParam: navigateBackWithParam,
   regExp: regExp,
   getMealApi: getMealApi,
   mealApi: mealApi,
}
// 获取旧约回收接口
function getJyhsApi(urlTail, param, callback) {
   var aipUrl = jyhsApi + urlTail
   request(aipUrl, param, callback)
}
// 获取共享接口
function getShareApi(urlTail, param, callback) {
   var aipUrl = shareApi + urlTail
   request(aipUrl, param, callback)
}
//获取商城接口
function getMealApi(urlTail, param, callback) {
   var aipUrl = mealApi + urlTail
   request(aipUrl, param, callback)
}
// 调用微信获取数据接口
function request(aipUrl, param, callback) {
   wx.request({
      url: aipUrl,
      data: param,
      method: 'POST',
      success: function(res) {
         console.log('【地址】 ' + aipUrl, '\n【参数】', param, '\n【成功】', res);
         var d = res.data
         if (d == '') return
         if (typeof(callback) == 'function') {
            callback(d)
         }
      },
      fail: function(res) {
         toast('网络请求失败！')
         console.log('【地址】 ' + aipUrl, '\n【参数】', param, '\n【失败】', res);
      },
   })
}

// 提示
function Toast(msg) {
   wx.showToast({
      title: msg
   })
}

function toastAllText(msg) {
   wx.showToast({
      title: msg,
      icon: 'none'
   })
}
// 带图标提示
function toast(msg) {
   wx.showToast({
      title: msg,
      image: '/resource/img/huaji.png',
   })
}
//不带标题提示
function Modal(text, confirmText = '朕知道了') {
   wx.showModal({
      content: text,
      cancelText: '',
      confirmText: confirmText,
   })
}
//带标题提示
function modal(msg, title,callback) {
   wx.showModal({
      title: title ? title : '温馨提示',
      content: msg,
      success:function(res){
         if (callback) callback(res)
      }
   })
}
// 删除提醒
function confirm(text, cancelText, confirmText, callback) {
   wx.showModal({
      content: text,
      showCancel: true,
      cancelColor: '#9E9E9E',
      cancelText: cancelText,
      confirmText: confirmText,
      confirmColor: '#76EE00',
      success: function(res) {
         console.log('confirm:success:', res)
         if (callback) callback(res.confirm)
      },
      fail: function(res) {
         if (callback) callback(res.cancel)
      },
   })
}
// 判断是否为空
function empty(val) {
   if (val == undefined || val == null || val == '' || val == 'undefined') {
      return true;
   }
   if (isArray(val)) {
      if (val.length == 0) {
         return true;
      }
   }
   return false;
}
//增加key和value
function addValueForKey(toDict, fromDict, keyArray = []) {
   console.log('toDict======', toDict)
   console.log('fromDict====', fromDict)
   if (!isArray(keyArray)) {
      toast('第3个传参类型错误')
      return toDict
   }
   var len = keyArray.length
   if (len == 0) {
      for (var key in fromDict) {
         console.log('key====',key)
         toDict[key] = fromDict[key]
      }
   } else {
      for (var i = 0; i < len; i++) {
         key = keyArray[i]
         if (fromDict[key]) {
            console.log('有key[' + i + ']==' + key)
            toDict[key] = fromDict[key]
         } else {
            console.log('没key[' + i + ']==' + key)
         }
      }
   }
   return toDict
}
//查对象在对象数组中的下标，不存在则返回-1，keyArray是要求比对的key
function getIndexInList(obj, list, keyArray = []) {
   var count = list.length
   if (count == 0 || !isArray(list) || empty(list))
      return -1
   for (var i = 0; i < count; i++) {
      if (twoObjIsSame(obj, list[i], keyArray)) {
         return i
      }
   }
   return -1
}
//判断两对象是否相同
function twoObjIsSame(obj, _obj, keyArray = []) {
   var len = keyArray.length
   if (len == 0) {
      for (var key in obj) {
         if (obj[key] != _obj[key]) {
            console.log('obj.' + key + '==' + obj[key] + ',_obj.' + key + '== ' + _obj[key])
            return 0
         }
      }
   } else {
      for (var i = 0; i < len; i++) {
         key = keyArray[i]
         if (obj[key] != _obj[key]) {
            console.log('obj.' + key + '==' + obj[key] + ',_obj.' + key + '== ' + _obj[key])
            return 0
         }
      }
   }
   return 1
}
//获取数据类型
function getType(array) {
   return Object.prototype.toString.call(array)
}
//是否数组
function isArray(obj) {
   return getType(obj) == '[object Array]'
}
//从对象获取经纬度
function getLoc(obj) {
   return {
      latitude: obj.latitude,
      longitude: obj.longitude
   }
}

function getNowFormatDate(type) {
   //type==1,只要日期 如果type==2 要日期时间
   var date = new Date();
   var seperator1 = "-";
   var seperator2 = ":";
   var month = date.getMonth() + 1;
   var strDate = date.getDate();
   if (month >= 1 && month <= 9) {
      month = "0" + month;
   }
   if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
   }

   var currentDate = date.getFullYear() + seperator1 + month + seperator1 + strDate

   if (type == 2) {
      currentDate += " " + date.getHours() + seperator2 + date.getMinutes() +
         seperator2 + date.getSeconds();
   }

   return currentDate;
}
//顾客点餐后通知生成小票
function setNoticeTicket(noti) {
   this.ticketNotice = noti
}

function noticeTicket(noti) {
   if (this.ticketNotice)
      this.ticketNotice(noti)
}
// 添加资金流水记录(用户)
function addMoneyRecord_User(param, callback) {
   this.getShareApi('money/Record/userAdd', param, function(res) {
      if (typeof(callback) === 'function') {
         callback(res)
      }
   })
}
//添加资金流水记录(商家)
function addMoneyRecord_Biz(param, callback) {
   this.getShareApi('money/Record/bizAdd', param, function(res) {
      if (typeof(callback) === 'function') {
         callback(res)
      }
   })
}
//返回页面(定时)
function navigateBack(obj, time) {
   setTimeout(function() {
      wx.navigateBack(obj)
   }, time)
}

//小数四舍五入
function round(val, num) {
   var n = Math.pow(10, num)
   return Math.round(val * n) / n
}


//小数四舍五入(返回字符串格式)
// '1.23' '5.00' '0.50'
function roundStr(val, num) {
   var num_str = round(val, num).toString()
   var x_num_str = num_str.split('.')[1]
   var count = x_num_str ? num - x_num_str.length : num
   num_str = x_num_str ? num_str : (num_str + '.')
   for (; count--; num_str += '0');
   return num_str
}

//统计字符串中包含给定的子字符串的个数
function countSubString(str, subStr) {
   var n = 0
   if (str && subStr) {
      n = (str.split(subStr)).length - 1
   }
   return n
}

//过滤字符串
function filterStr(str, flag) {
   var result = ''
   var n = 0;
   if (str && flag) {
      result = str.split('').map(char => {
         if (char === flag) {
            n++
         }
         return char === flag && n > 1 ? '' : char
      }).join('')
   }
   return result
}

//更新对象指定属性值
function updateKeyForValue(obj, keyArray = [], valArray = []) {
   if (!(obj && typeof(obj) == 'object')) {
      console.log('第1个传参类型错误')
      return false
   }
   if (!isArray(keyArray)) {
      console.log('第2个传参类型错误')
      return false
   }
   if (!isArray(valArray)) {
      console.log('第3个传参类型错误')
      return false
   }
   var len = keyArray.length
   var num = valArray.length
   if (len > 0 && num > 0) {
      for (var i = 0; i < len; i++) {
         var key = keyArray[i]
         var val = valArray[i]
         if (obj[key]) {
            obj[key] = val ? val : ''
         }
      }
   }
   return true
}

//更新用户余额
function updateUserBalance(New_Balance) {
   var userInfo = wx.getStorageSync('userInfo')
   if (userInfo) {
      updateKeyForValue(userInfo, ['User_Balance'], [New_Balance])
      wx.setStorageSync('userInfo', userInfo)
      getApp().Data.userInfo = userInfo
      console.log('updateUserBalance===', userInfo)
   }
}

//返回带参数
function navigateBackWithParam(pageNo, param, pageName) {
   //回跳页面
   wx.navigateBack({
      delta: pageNo,
      success: function (res) {
         var page = ''
         var platform = wx.getSystemInfoSync().platform
         var pageCount = getCurrentPages().length
         console.log('getCurrentPages()=====', getCurrentPages())
         console.log('platform===', platform)
         //IOS
         if (platform === 'ios') {
            //获取当前栈顶的页面
            page = getCurrentPages()[pageCount - pageNo - 1]
         }
         //Android 或者 模拟器
         else if (platform === 'android' || platform === 'devtools') {
            //获取当前栈顶的页面
            page = getCurrentPages()[pageCount - pageNo]
            // console.log('获取当前栈顶的页面page========',page)
            if (!empty(pageName)) {
               //重新获取page
               // console.log('pageName=====', pageName)
               if (page.route != pageName) {
                  for (var i = 0; i < pageCount; i++) {
                     if (pageName == getCurrentPages()[i].route) {
                        page = getCurrentPages()[i]
                        break
                     }
                  }
                  // page = getCurrentPages()[pageCount - pageNo - 1];
               }
            }
         }
         console.log('page===', page)
         if (empty(page)) {
            return
         }
         //传递参数
         page.onShow(param)
         console.log('跳转回去')
      }
   })
}

//正则表达式
function regExp(str, flag) {
   //flag=1 校验是否带有小数
   //flag=2 校验是否中文名称组成
   //flag=3 校验是否全由8位数字组成
   //flag=4 校验电话码格式
   //flag=5 校验邮件地址是否合法
   //flag=6 校验日期格式为yyyy-mm-dd

   var reg = ''
   if (flag == 1) {
      reg = /^\d+\.\d+$/
   }
   if (flag == 2) {
      reg = /^[\u4E00-\u9FA5]{2,4}$/
   }
   if (flag == 3) {
      reg = /^[0-9]{8}$/
   }
   if (flag == 4) {
      reg = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/
   }
   if (flag == 5) {
      reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
   }
   if (flag == 6) {
      reg = /^(\d{4})-(\d{2})-(\d{2})$/
   }

   return reg.test(str)
}

